package byx.container.annotation.extension.impl;

import byx.container.annotation.annotation.Order;
import byx.container.annotation.annotation.Register;
import byx.container.annotation.extension.core.ClassPostProcessorContext;
import byx.container.annotation.extension.core.ClassProcessorContext;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 处理条件注入的方法
 */
@Order(Integer.MAX_VALUE)
public class ConditionalMethodProcessor extends ConditionalRegisterProcessor {
    public ConditionalMethodProcessor(ClassScanner classScanner, List<ConditionalAnnotationHandler<?>> handlers) {
        super(classScanner, handlers);
    }

    @Override
    public List<ClassPostProcessorContext> process(ClassProcessorContext ctx) {
        Class<?> type = ctx.getType();
        if (type.isAnnotationPresent(Register.class)) {
            return processMethods(type, ctx);
        }

        ConditionalAnnotationHandler<?> handler = findConditionalAnnotationHandler(type);
        if (handler != null && needToRegister(type, handler, ctx)) {
            return processMethods(type, ctx);
        }

        return Collections.emptyList();
    }

    private List<ClassPostProcessorContext> processMethods(Class<?> type, ClassProcessorContext ctx) {
        List<ClassPostProcessorContext> contexts = new ArrayList<>();
        for (Method method : type.getMethods()) {
            ConditionalAnnotationHandler<?> handler = findConditionalAnnotationHandler(method);
            if (handler != null && needToRegister(method, handler, ctx)) {
                contexts.add(getMethodContext(method));
            }
        }
        return contexts;
    }
}
